#!/bin/bash

temp="./temp"

[ -z "$1" -o -z "$2" ] && echo "`basename $0`: iscsi_ip iscsi_iqn" && exit 1
isc_ip="$1"
isc_iqn=""
isc_iqn=`iscsiadm -m discovery -t st -p "$isc_ip" | awk '{ print $NF }' | grep "$2" | head -n 1`
[ -z "$isc_iqn" ] && echo "target iqn not exists!" && exit 2
isc_name=`echo "$isc_iqn" | awk -F":" '{print $NF}'`

echo "Target IP=$isc_ip, IQN=$isc_iqn"
iscsiadm -m node --login
[ $? -ne 0 ] && echo "login failed! quit!" && exit 3


# default we search part-1
isc_dev=""
while [ "$isc_dev" == "" ]
do
  isc_dev=`find /dev/disk/by-path/ | grep $isc_ip | grep $isc_iqn | grep part1`
  sleep 1
done
mkdir "$temp" 2>/dev/null
umount "$temp" 2>/dev/null
mount "$isc_dev" "$temp"

# copy boot image
bin_linux=`find $temp/boot/ -name "vmlinuz*generic" | head -n 1`
bin_initrd=`find $temp/boot/ -name "initrd.img*generic" | head -n 1`
echo "Copying $bin_linux as kernel image......"
cp "$bin_linux" ./linux
echo "Copying $bin_initrd as initrd image......"
cp "$bin_initrd" ./initrd

# change host name
echo "Change host name to \"$isc_name\""
echo "$isc_name" > "$temp/etc/hostname"

# change disk id
par_uuid=`blkid "$isc_dev" | awk '{gsub("UUID=","",$2); gsub("\"","",$2); print $2}'`
echo "Change fstab to \"$par_uuid\""
cat "$temp/etc/fstab" | \
awk 'BEGIN{uuid="'"$par_uuid"'"}{\
  if (($2=="/")&&($1~/^UUID=.*/)){\
    gsub(/^UUID=[a-zA-Z0-9\-]+/,"UUID="uuid,$0);}\
  print $0}' > "$temp/etc/fstab"

# Now we are done, umount the iscsi target
umount "$temp"
iscsiadm -m node --logout

# really make iso
mv ./isolinux.cfg ./isolinux.bck
echo "PROMPT 0
DEFAULT linux
LABEL linux
  KERNEL linux
  APPEND root=UUID=$par_uuid rw ip=dhcp ISCSI_INITIATOR=iqn.2012-03.lance.client:test-001 ISCSI_TARGET_NAME=$isc_iqn ISCSI_TARGET_IP=$isc_ip ISCSI_TARGET_PORT=3260 initrd=initrd
" > ./isolinux.cfg

mkisofs -o /pbfd/ISO/$isc_name.iso \
-b isolinux.bin \
-c boot.cat \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
./

mv ./isolinux.bck ./isolinux.cfg
